import { useUserStore } from '@/stores'
import axios, { AxiosError, type Method } from 'axios'
import { showToast } from 'vant'
import router from '@/router'

export const baseURL = 'https://consult-api.itheima.net'
const instance = axios.create({
  //  1. 基础地址，超时时间
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    //  2. 携带token
    const store = useUserStore()
    // 在ts里要添加类型守卫 config.headers
    if (store.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.user.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    //  3. 处理业务失败
    if (res.data.code !== 10000) {
      showToast(res.data.message)
      return Promise.reject(res.data)
    }
    // 4. 摘取核心响应数据
    return res.data
  },
  (err: AxiosError) => {
    //  5. 处理401错误
    if (err.response?.status === 401) {
      // 清除登录信息
      const store = useUserStore()
      store.delUser()
      // 跳转到登录页面
      router.push({
        path: '/login',
        query: {
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(err)
  }
)

export default instance

type Data<T> = {
  code: number,
  message: string,
  data: T
}
export const request = <T>(url: string, method: Method = 'GET', sumitData?: object) => {
  // request 第一个参数使用any ，但是eslint报错 使用unknown代替
  return instance.request<unknown, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: sumitData
  })
}
